package cn.suse.android;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import cn.suse.android.adapter.FriendRecordAdapter;
import cn.suse.android.adapter.RepasteListViewAdapter;
import cn.suse.android.entity.Circle;
import cn.suse.android.entity.FriendsRecord;
import cn.suse.android.entity.Group;
import cn.suse.android.entity.RecordActive;
import cn.suse.android.entity.Repaste;
import cn.suse.android.entity.User;
import cn.suse.android.entity.Vote;
import cn.suse.android.exception.AppException;
import cn.suse.android.logic.FriendsRecordParse;
import cn.suse.android.logic.GroupParse;
import cn.suse.android.logic.RepasteParse;
import cn.suse.android.logic.UserParse;
import cn.suse.android.net.AppHelper;
import cn.suse.android.share.Constant;
import cn.suse.android.share.MainApplication;
import cn.suse.android.utils.StringUtils;
import cn.suse.android.widget.MyQuickAction;
import cn.suse.android.widget.PullToRefreshListView;
import cn.suse.android.widget.PullToRefreshListView.OnRefreshListener;
import cn.suse.android.widget.QuickActionGrid;
import cn.suse.android.widget.QuickActionWidget;
import cn.suse.android.widget.QuickActionWidget.OnQuickActionClickListener;
import cn.suse.android.widget.ScrollLayout;
public class MainActivity extends BaseActivity {
	
	private ImageView mHeadLogo;
	private ImageView location;
	private TextView mHeadTitle;
	private TextView usernameTextView;
	private ImageButton mHead_write;
	private QuickActionGrid mGrid;
	
	private ScrollLayout mScrollLayout;
	private String[] mHeadTitles;
	private int mViewCount;
	private RadioButton[] mButtons;
	private int mCurSel;
	
	private RadioButton homeRadioButton;
	private RadioButton messageRadioButton;
	private RadioButton friendRadioButton;
	private RadioButton applyRadioButton;
	private ImageView moreImageView;
	
	public static  MainActivity instance;
	//好友记录
	private List<RecordActive> friends = new ArrayList<RecordActive>() ;
	private List<Repaste> repastes = new ArrayList<Repaste>();
	private List<Repaste> friendRepastes = new ArrayList<Repaste>();
	private List<FriendsRecord> friendRecords = new ArrayList<FriendsRecord>();
	
	private RepasteListViewAdapter repasteListViewAdapter;
	private RepasteListViewAdapter friendRepasteListViewAdapter;
	private FriendRecordAdapter friendRecordAdapter;
	
	private PullToRefreshListView repasteListView;
	private PullToRefreshListView friendRepasteListView;
	private PullToRefreshListView friendRecordListView;
	
	private TextView lvRepaste_foot_more;
	private TextView lvFriend_repaste_foot_more;
	private TextView lvFriend_record_foot_more;
	
	private ProgressBar lvRepaste_foot_progress;
	private ProgressBar lvFriend_repaste_foot_progress;
	private ProgressBar lvFriend_record_foot_progress;
	
	private View lvRepaste_footer;
	private View lvFriend_repaste_footer;
	private View lvFriend_record_footer;
	
	private Handler lvRepasteHandler;
	private Handler lvFriendRepasteHandler;
	private Handler lvFriendRecordHandler;
	
	private int lvRepasteNumData;
	private int lvFriendRepasteNumData;
	private int lvFriendRecordNumData;
	
	private int curHomeCatalog = Repaste.CATALOG_ALL;
	//首页顶部按钮
	private Button frame_home_btn_friends;
	private Button frame_home_btn_friend_repaste;
	private Button frame_home_btn_friend_record;
	
	private List<Group> groupIds;
	private ListView groupListView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        instance = this;
		this.initHeadView();
        this.initFootBar();
        this.initPageScroll();        
        this.initFrameButton();
//        this.initBadgeView();
        this.initQuickActionGrid();
        this.initFrameListView();
        new UserTask().execute();
//        new NewTask(MainActivity.this,R.string.load_friend_active,R.string.load_friend_active_fail).execute(null);
    }
    
	/**
	 * 初始化各个按钮
	 */
	private void initFrameButton() {
		// TODO Auto-generated method stub
		frame_home_btn_friends = (Button) findViewById(R.id.frame_btn_friends_update);
		frame_home_btn_friend_repaste = (Button) findViewById(R.id.frame_btn_circle_update);
		frame_home_btn_friend_record = (Button) findViewById(R.id.frame_btn_vote);
		frame_home_btn_friends.setEnabled(false);
		frame_home_btn_friends.setOnClickListener(frameHomeBtnClick(frame_home_btn_friends,Repaste.CATALOG_ALL));
		frame_home_btn_friend_repaste.setOnClickListener(frameHomeBtnClick(frame_home_btn_friend_repaste,Circle.CATALOG_CIRCLE));
		frame_home_btn_friend_record.setOnClickListener(frameHomeBtnClick(frame_home_btn_friend_record,Vote.CATALOG_VOTE));
	}

	private View.OnClickListener frameHomeBtnClick(final Button btn,final int category){
		return new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(btn == frame_home_btn_friends){
					frame_home_btn_friends.setEnabled(false);
				}else{
					frame_home_btn_friends.setEnabled(true);
				}
				if(btn == frame_home_btn_friend_repaste){
					frame_home_btn_friend_repaste.setEnabled(false);
				}else{
					frame_home_btn_friend_repaste.setEnabled(true);
				}
				if(frame_home_btn_friend_record == btn){
					frame_home_btn_friend_record.setEnabled(false);
				}else{
					frame_home_btn_friend_record.setEnabled(true);
				}
				curHomeCatalog = category;
				if(frame_home_btn_friends == btn){
					repasteListView.setVisibility(View.VISIBLE);
					friendRepasteListView.setVisibility(View.GONE);
					friendRecordListView.setVisibility(View.GONE);
					lvRepaste_foot_more.setText(R.string.load_more);
					lvRepaste_foot_progress.setVisibility(View.GONE);
					loadLvRepasteData(curHomeCatalog, 0, lvRepasteHandler, Constant.LISTVIEW_ACTION_CHANGE_CATALOG);
				}else if(frame_home_btn_friend_repaste == btn){
					repasteListView.setVisibility(View.GONE);
					friendRecordListView.setVisibility(View.GONE);
					friendRepasteListView.setVisibility(View.VISIBLE);
					if(friendRepastes.size()>0){
						lvFriend_repaste_foot_more.setText(R.string.load_more);
						lvFriend_repaste_foot_progress.setVisibility(View.GONE);
					}
					loadLvFriendRepasteData(curHomeCatalog,0,lvFriendRepasteHandler,Constant.LISTVIEW_ACTION_CHANGE_CATALOG);
				}else if(frame_home_btn_friend_record == btn){
					repasteListView.setVisibility(View.GONE);
					friendRepasteListView.setVisibility(View.GONE);
					friendRecordListView.setVisibility(View.VISIBLE);
					if(friendRecords.size()>0){
						lvFriend_record_foot_more.setText(R.string.load_more);
						lvFriend_record_foot_progress.setVisibility(View.GONE);
					}
					loadLvFriendRecordData(curHomeCatalog,0,lvFriendRecordHandler,Constant.LISTVIEW_ACTION_CHANGE_CATALOG);
				}
			}
		};
	}
	@Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	if(mViewCount == 0) mViewCount = 4;
    	if(mCurSel == 0 && !homeRadioButton.isChecked()) {
    		homeRadioButton.setChecked(true);
    		messageRadioButton.setChecked(false);
    		friendRadioButton.setChecked(false);
    		applyRadioButton.setChecked(false);
    	}
    	//读取左右滑动配置
//    	mScrollLayout.setIsScroll(appContext.isScroll());
    }
	 /**
	 * 初始化ListView
	 */
	private void initFrameListView() {
		// TODO Auto-generated method stub
		//初始化ListView视图
		initRepasteListView();
		initFriendRepasteListView();
		initFriendRecordListView();
        initFrameListViewData();
	}

	/**
	 * 初始化LIstView数据
	 */
	private void initFrameListViewData() {
		// TODO Auto-generated method stub
		lvRepasteHandler = getLvHandler(repasteListView, repasteListViewAdapter, lvRepaste_foot_more, lvRepaste_foot_progress, Constant.PAGE_SIZE);
		lvFriendRepasteHandler = getLvHandler(friendRepasteListView, friendRepasteListViewAdapter, lvFriend_repaste_foot_more, lvFriend_repaste_foot_progress, Constant.PAGE_SIZE);
		lvFriendRecordHandler = getLvHandler(friendRecordListView, friendRecordAdapter, lvFriend_record_foot_more, lvFriend_record_foot_progress, Constant.PAGE_SIZE);
		if(repastes.isEmpty()){
			loadLvRepasteData(curHomeCatalog, 0, lvRepasteHandler, Constant.LISTVIEW_ACTION_INIT);
		}
	}

	  /**
	   * 获取热门转帖数据
	 * @param curRepasteCatalog2
	 * @param pageIndex
	 * @param lvRepasteHandler2
	 * @param listviewActionInit
	 */
	private void loadLvRepasteData(final int catalog, final int pageIndex,
			final Handler lvRepasteHandler,final int action) {
		// TODO Auto-generated method stub
		new Thread(){
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if(action == Constant.LISTVIEW_ACTION_REFRESH || action == Constant.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				Bundle bundle = null;
				if(pageIndex != 0&&pageIndex != -1){
					bundle = new Bundle();
					bundle.putString("start", ""+pageIndex);
				}
				String json = AppHelper.getFriendActive(MainActivity.instance.kaixin, MainActivity.this, Repaste.PATH_STRING, bundle, "GET");
				List<Repaste> lists = new RepasteParse().parseData(json);
				msg.what = lists.size();
				msg.obj = lists;
				msg.arg1 = action;
				msg.arg2 = Constant.LISTVIEW_DATATYPE_REPASTE;
                if(curHomeCatalog == catalog)
                	lvRepasteHandler.sendMessage(msg);
			};
		}.start();
	}
	private void loadLvFriendRecordData(final int catalog, final int pageIndex,
			final Handler lvFriendRepasteHandler,final int action) {
		// TODO Auto-generated method stub
		new Thread(){
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if(action == Constant.LISTVIEW_ACTION_REFRESH || action == Constant.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
//				String type = "";
//				switch (catalog) {
//				case Circle.CATALOG_CIRCLE:
//					type = Circle.TYPE_LATEST;
//					break;
//				case Circle.CATALOG_RECOMMEND:
//					type = Circle.TYPE_RECOMMEND;
//					break;
//				}
				Bundle bundle = null;
				if(pageIndex != 0&&pageIndex != -1){
					bundle = new Bundle();
					bundle.putString("start", ""+pageIndex);
				}
				String json = AppHelper.getFriendActive(MainActivity.instance.kaixin, MainActivity.this, FriendsRecord.PATH_STRING, bundle, "GET");
				List<FriendsRecord> lists  = new FriendsRecordParse().parseData(json);				
				msg.what = lists.size();
				msg.obj = lists;
				msg.arg1 = action;
				msg.arg2 = Constant.LISTVIEW_DATATYPE_FRIEND_RECORD;
                if(curHomeCatalog == catalog)
                	lvFriendRecordHandler.sendMessage(msg);
			};
		}.start();
	} 
	private void loadLvFriendRepasteData(final int catalog, final int pageIndex,
			final Handler lvFriendRepasteHandler,final int action) {
		// TODO Auto-generated method stub
		new Thread(){
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if(action == Constant.LISTVIEW_ACTION_REFRESH || action == Constant.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				String type = "";
				switch (catalog) {
				case Circle.CATALOG_CIRCLE:
					type = Circle.TYPE_LATEST;
					break;
				case Circle.CATALOG_RECOMMEND:
					type = Circle.TYPE_RECOMMEND;
					break;
				}
				Bundle bundle = null;
				if(pageIndex != 0&&pageIndex != -1){
					bundle = new Bundle();
					bundle.putString("start", ""+pageIndex);
				}
				String json = AppHelper.getFriendActive(MainActivity.instance.kaixin, MainActivity.this, Repaste.FRIEND_REPASTE_PATH, bundle, "GET");
//				System.out.println(json);
				List<Repaste> lists  = new RepasteParse().parseData(json);				
				msg.what = lists.size();
				msg.obj = lists;
				msg.arg1 = action;
				msg.arg2 = Constant.LISTVIEW_DATATYPE_BLOG;
                if(curHomeCatalog == catalog)
                	lvFriendRepasteHandler.sendMessage(msg);
			};
		}.start();
	} 
	/**
     * 获取listview的初始化Handler
     * @param mPullToRefreshListView
     * @param adapter
     * @return
     */
    private Handler getLvHandler(final PullToRefreshListView mPullToRefreshListView,final BaseAdapter adapter,final TextView more,final ProgressBar progress,final int pageSize){
    	return new Handler(){
			public void handleMessage(Message msg) {
				if(msg.what >= 0){
//					//listview数据处理
					handleLvData(msg.what, msg.obj, msg.arg2, msg.arg1);
					if(msg.what < pageSize){
						mPullToRefreshListView.setTag(Constant.LISTVIEW_DATA_FULL);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_full);
					}else if(msg.what == pageSize){
						mPullToRefreshListView.setTag(Constant.LISTVIEW_DATA_MORE);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);
					}
				}
				else if(msg.what == -1){
					//有异常--显示加载出错 & 弹出错误消息
					mPullToRefreshListView.setTag(Constant.LISTVIEW_DATA_MORE);
					more.setText(R.string.load_error);
					((AppException)msg.obj).makeToast(MainActivity.this);
				}
				if(adapter.getCount()==0){
					mPullToRefreshListView.setTag(Constant.LISTVIEW_DATA_EMPTY);
					more.setText(R.string.load_empty);
				}
				progress.setVisibility(ProgressBar.GONE);
				if(msg.arg1 == Constant.LISTVIEW_ACTION_REFRESH){
					mPullToRefreshListView.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
					mPullToRefreshListView.setSelection(0);
				}else if(msg.arg1 == Constant.LISTVIEW_ACTION_CHANGE_CATALOG){
					mPullToRefreshListView.onRefreshComplete();
					mPullToRefreshListView.setSelection(0);
				}
			}
		};
    }
    private void handleLvData(int what,Object obj,int objtype,int actiontype){
//    	Notice notice = null;
		switch (actiontype) {
			case Constant.LISTVIEW_ACTION_INIT:
			case Constant.LISTVIEW_ACTION_REFRESH:
			case Constant.LISTVIEW_ACTION_CHANGE_CATALOG:
				int newdata = 0;//新加载数据-只有刷新动作才会使用到
				switch (objtype) {
					case Constant.LISTVIEW_DATATYPE_REPASTE:
						List<Repaste> lists = (List<Repaste>)obj;
						lvRepasteNumData = what;
						if(actiontype == Constant.LISTVIEW_ACTION_REFRESH){
							if(repastes.size() > 0){
								for(Repaste repaste:lists){
									boolean b = false;
									for(Repaste repaste1:repastes){
										if(repaste.getTitle().equals(repaste1.getTitle())){
											b = true;
											break;
										}
									}
									if(!b) newdata++;
								}
							}else{
								newdata = what;
							}
						}
						repastes.clear();//先清除原有数据
						repastes.addAll(lists);
//						repasteListViewAdapter.setLists(repastes);
						break;
					case Constant.LISTVIEW_DATATYPE_BLOG:
						List<Repaste> friend_repaste = (List<Repaste>)obj;
						lvFriendRepasteNumData = what;
						if(actiontype == Constant.LISTVIEW_ACTION_REFRESH){
							if(friendRepastes.size() > 0){
								for(Repaste repaste:friend_repaste){
									boolean b = false;
									for(Repaste repaste1:friendRepastes){
										if(repaste.getTitle().equals(repaste1.getTitle())){
											b = true;
											break;
										}
									}
									if(!b) newdata++;
								}
							}else{
								newdata = what;
							}
						}
						friendRepastes.clear();//先清除原有数据
						friendRepastes.addAll(friend_repaste);
						break;
					case Constant.LISTVIEW_DATATYPE_FRIEND_RECORD:
						@SuppressWarnings("unchecked")
						List<FriendsRecord> frs = (List<FriendsRecord>)obj;
						lvFriendRecordNumData = what;
						if(actiontype == Constant.LISTVIEW_ACTION_REFRESH){
							if(friendRecords.size() > 0){
								for(FriendsRecord friendRecord : frs){
									boolean b = false;
									for(FriendsRecord friendRecord2 : friendRecords){
										if(friendRecord.getRid().equals(friendRecord2.getRid())){
											b = true;
											break;
										}
									}
									if(!b) newdata++;
								}
							}else{
								newdata = what;
							}
						}
						friendRecords.clear();//先清除原有数据
						friendRecords.addAll(frs);
						break;
//					case Constant.LISTVIEW_DATATYPE_TWEET:
//						TweetList tlist = (TweetList)obj;
//						notice = tlist.getNotice();
//						lvTweetSumData = what;
//						if(actiontype == Constant.LISTVIEW_ACTION_REFRESH){
//							if(lvTweetData.size() > 0){
//								for(Tweet tweet1 : tlist.getTweetlist()){
//									boolean b = false;
//									for(Tweet tweet2 : lvTweetData){
//										if(tweet1.getId() == tweet2.getId()){
//											b = true;
//											break;
//										}
//									}
//									if(!b) newdata++;
//								}
//							}else{
//								newdata = what;
//							}
//						}
//						lvTweetData.clear();//先清除原有数据
//						lvTweetData.addAll(tlist.getTweetlist());
//						break;
//					case Constant.LISTVIEW_DATATYPE_ACTIVE:
//						ActiveList alist = (ActiveList)obj;
//						notice = alist.getNotice();
//						lvActiveSumData = what;
//						if(actiontype == Constant.LISTVIEW_ACTION_REFRESH){
//							if(lvActiveData.size() > 0){
//								for(Active active1 : alist.getActivelist()){
//									boolean b = false;
//									for(Active active2 : lvActiveData){
//										if(active1.getId() == active2.getId()){
//											b = true;
//											break;
//										}
//									}
//									if(!b) newdata++;
//								}
//							}else{
//								newdata = what;
//							}
//						}
//						lvActiveData.clear();//先清除原有数据
//						lvActiveData.addAll(alist.getActivelist());
//						break;
//					case Constant.LISTVIEW_DATATYPE_MESSAGE:
//						MessageList mlist = (MessageList)obj;
//						notice = mlist.getNotice();
//						lvMsgSumData = what;
//						if(actiontype == Constant.LISTVIEW_ACTION_REFRESH){
//							if(lvMsgData.size() > 0){
//								for(Messages msg1 : mlist.getMessagelist()){
//									boolean b = false;
//									for(Messages msg2 : lvMsgData){
//										if(msg1.getId() == msg2.getId()){
//											b = true;
//											break;
//										}
//									}
//									if(!b) newdata++;
//								}
//							}else{
//								newdata = what;
//							}
//						}
//						lvMsgData.clear();//先清除原有数据
//						lvMsgData.addAll(mlist.getMessagelist());
//						break;
//				}
//				if(actiontype == Constant.LISTVIEW_ACTION_REFRESH){
//					//提示新加载数据
//					if(newdata >0){
//						NewDataToast.makeText(this, getString(R.string.new_data_toast_message, newdata), appContext.isAppSound()).show();
//					}else{
//						NewDataToast.makeText(this, getString(R.string.new_data_toast_none), false).show();
//					}
				}
				break;
			case Constant.LISTVIEW_ACTION_SCROLL:
				switch (objtype) {
					case Constant.LISTVIEW_DATATYPE_REPASTE:
						@SuppressWarnings("unchecked")
						List<Repaste> lists = (List<Repaste>)obj;
						lvFriendRepasteNumData += what;
						if(repastes.size() > 0){
							for(Repaste repaste :lists){
								boolean b = false;
								for(Repaste repaste2 :repastes){
									if(repaste.getTitle().equals(repaste2.getTitle())){
										b = true;
										break;
									}
								}
								if(!b) repastes.add(repaste);
							}
						}else{
							repastes.addAll(lists);
						}
						break;
					case Constant.LISTVIEW_DATATYPE_BLOG:
						@SuppressWarnings("unchecked")
						List<Repaste> ls = (List<Repaste>)obj;
						lvRepasteNumData += what;
						if(friendRepastes.size() > 0){
							for(Repaste repaste :ls){
								boolean b = false;
								for(Repaste repaste2 :friendRepastes){
									if(repaste.getTitle().equals(repaste2.getTitle())){
										b = true;
										break;
									}
								}
								if(!b) friendRepastes.add(repaste);
							}
						}else{
							friendRepastes.addAll(ls);
						}
						break;
					case Constant.LISTVIEW_DATATYPE_FRIEND_RECORD:
						@SuppressWarnings("unchecked")
						List<FriendsRecord> friends = (List<FriendsRecord>)obj;
						lvFriendRecordNumData += what;
						if(friendRecords.size() > 0){
							for(FriendsRecord friendsRecord :friends){
								boolean b = false;
								for(FriendsRecord friendsRecord2 :friendRecords){
									if(friendsRecord.getRid().equals(friendsRecord2.getRid())){
										b = true;
										break;
									}
								}
								if(!b) friendRecords.add(friendsRecord);
							}
						}else{
							friendRecords.addAll(friends);
						}
						break;
//					case Constant.LISTVIEW_DATATYPE_TWEET:
//						TweetList tlist = (TweetList)obj;
//						notice = tlist.getNotice();
//						lvTweetSumData += what;
//						if(lvTweetData.size() > 0){
//							for(Tweet tweet1 : tlist.getTweetlist()){
//								boolean b = false;
//								for(Tweet tweet2 : lvTweetData){
//									if(tweet1.getId() == tweet2.getId()){
//										b = true;
//										break;
//									}
//								}
//								if(!b) lvTweetData.add(tweet1);
//							}
//						}else{
//							lvTweetData.addAll(tlist.getTweetlist());
//						}
//						break;
//					case Constant.LISTVIEW_DATATYPE_ACTIVE:
//						ActiveList alist = (ActiveList)obj;
//						notice = alist.getNotice();
//						lvActiveSumData += what;
//						if(lvActiveData.size() > 0){
//							for(Active active1 : alist.getActivelist()){
//								boolean b = false;
//								for(Active active2 : lvActiveData){
//									if(active1.getId() == active2.getId()){
//										b = true;
//										break;
//									}
//								}
//								if(!b) lvActiveData.add(active1);
//							}
//						}else{
//							lvActiveData.addAll(alist.getActivelist());
//						}
//						break;
//					case Constant.LISTVIEW_DATATYPE_MESSAGE:
//						MessageList mlist = (MessageList)obj;
//						notice = mlist.getNotice();
//						lvMsgSumData += what;
//						if(lvMsgData.size() > 0){
//							for(Messages msg1 : mlist.getMessagelist()){
//								boolean b = false;
//								for(Messages msg2 : lvMsgData){
//									if(msg1.getId() == msg2.getId()){
//										b = true;
//										break;
//									}
//								}
//								if(!b) lvMsgData.add(msg1);
//							}
//						}else{
//							lvMsgData.addAll(mlist.getMessagelist());
//						}
//						break;
				}
				break;
		}
		return;
    }
    /**
     * 初始化头部视图
     */
    private void initHeadView()
    {
    	mHeadLogo = (ImageView)findViewById(R.id.main_head_logo);
    	mHeadTitle = (TextView)findViewById(R.id.main_head_title);
    	mHead_write = (ImageButton)findViewById(R.id.main_head_write);
    	usernameTextView = (TextView)findViewById(R.id.username);
//    	mHead_search.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View v) {
//				Constant.showSearch(v.getContext());
//			}
//		});
//    	mHeadPub_post.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View v) {
//				Constant.showQuestionPub(v.getContext());
//			}
//		});
//    	mHeadPub_tweet.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View v) {
//				Constant.showTweetPub(Main.this);
//			}
//		});
    }
    /**
     * 初始化底部栏
     */
    private void initFootBar()
    {
    	homeRadioButton = (RadioButton)findViewById(R.id.main_footbar_home);
    	messageRadioButton = (RadioButton)findViewById(R.id.main_footbar_message);
    	friendRadioButton = (RadioButton)findViewById(R.id.main_footbar_friend);
    	applyRadioButton = (RadioButton)findViewById(R.id.main_footbar_apply);
    	
    	moreImageView = (ImageView)findViewById(R.id.main_footbar_more);
    	moreImageView.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {    			
    			//展示快捷栏&判断是否登录&是否加载文章图片
//    			Constant.showSettingLoginOrLogout(MainActivity.this, mGrid.getQuickAction(0));
    			mGrid.show(v);
    		}
    	});    	
    }
    /**
     * 初始化水平滚动翻页
     */
    private void initPageScroll()
    {
    	mScrollLayout = (ScrollLayout) findViewById(R.id.main_scrolllayout);
    	
    	LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_linearlayout_footer);
    	mHeadTitles = getResources().getStringArray(R.array.head_titles);
    	mViewCount = mScrollLayout.getChildCount();
    	mButtons = new RadioButton[mViewCount];
    	
    	for(int i = 0; i < mViewCount; i++)
    	{
    		mButtons[i] = (RadioButton) linearLayout.getChildAt(i*2);
    		mButtons[i].setTag(i);
    		mButtons[i].setChecked(false);
    		mButtons[i].setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					int pos = (Integer)(v.getTag());
					//点击当前项刷新
	    			if(mCurSel == pos) {
		    			switch (pos) {
						case 0://首页
							if(homeRadioButton.getVisibility() == View.VISIBLE)
//								homeRadioButton.clickRefresh();
								;
							else
//								lvBlog.clickRefresh();
							break;	
						case 1://消息
//							lvQuestion.clickRefresh();
							break;
						case 2://好友
//							lvTweet.clickRefresh();
							break;
						case 3://应用
							if(applyRadioButton.getVisibility() == View.VISIBLE)
//								lvActive.clickRefresh();
								;
							else
//								lvMsg.clickRefresh();
							break;
						}
	    			}
					setCurPoint(pos);
					mScrollLayout.snapToScreen(pos);
				}
			});
    	}
    	
    	//设置第一显示屏
    	mCurSel = 0;
    	mButtons[mCurSel].setChecked(true);
    	
    	mScrollLayout.SetOnViewChangeListener(new ScrollLayout.OnViewChangeListener() {
			public void OnViewChange(int viewIndex) {
				//切换列表视图-如果列表数据为空：加载数据
				switch (viewIndex) {
				case 0://资讯
//					if(lvNewsData.isEmpty()) {
//						loadLvNewsData(curNewsCatalog, 0, lvNewsHandler, Constant.LISTVIEW_ACTION_INIT);
//					}
					break;	
				case 1://问答
//					if(lvQuestionData.isEmpty()) {
//						loadLvQuestionData(curQuestionCatalog, 0, lvQuestionHandler, Constant.LISTVIEW_ACTION_INIT);
//					} 
					break;
				case 2://动弹
//					if(lvTweetData.isEmpty()) {
//						loadLvTweetData(curTweetCatalog, 0, lvTweetHandler, Constant.LISTVIEW_ACTION_INIT);
//					}
					break;
				case 3://动态
//					if(lvActive.getVisibility() == View.VISIBLE) {
//						if(lvActiveData.isEmpty()) {
//							loadLvActiveData(curActiveCatalog, 0, lvActiveHandler, Constant.LISTVIEW_ACTION_INIT);
//						}
//					} else {
//						if(lvMsgData.isEmpty()) {
//							loadLvMsgData(0, lvMsgHandler, Constant.LISTVIEW_ACTION_INIT);
//						}
//					}
					break;
				}
				setCurPoint(viewIndex);
			}
		});
    }
    /**
     * 设置底部栏当前焦点
     * @param index
     */
    private void setCurPoint(int index)
    {
    	if (index < 0 || index > mViewCount - 1 || mCurSel == index)
    		return;
   	
    	mButtons[mCurSel].setChecked(false);
    	mButtons[index].setChecked(true);    	
    	mHeadTitle.setText(mHeadTitles[index]);    	
    	mCurSel = index;
    	
    	mHead_write.setVisibility(View.GONE);
		//头部logo、发帖、发动弹按钮显示
    	if(index == 0){
    		mHeadLogo.setImageResource(R.drawable.frame_logo_news);
    		mHead_write.setVisibility(View.VISIBLE);
    	}
    	else if(index == 1){
    		mHeadLogo.setImageResource(R.drawable.frame_logo_post);
//    		mHeadPub_post.setVisibility(View.VISIBLE);
    	}
    	else if(index == 2){
    		mHeadLogo.setImageResource(R.drawable.frame_logo_tweet);
//    		mHeadPub_tweet.setVisibility(View.VISIBLE);
    	}
    	//处理通知信息
    	else if(index == 3){
    		mHeadLogo.setImageResource(R.drawable.frame_logo_active);
//    		mHeadPub_tweet.setVisibility(View.VISIBLE);
    		
    		//判断登录
//			int uid = appContext.getLoginUid();
//			if(uid == 0){
//				Constant.showLoginDialog(Main.this);
//				return;
//			}    		
    		
//			if(bv_atme.isShown()) 
//				frameActiveBtnOnClick(framebtn_Active_atme, ActiveList.CATALOG_ATME, Constant.LISTVIEW_ACTION_CHANGE_CATALOG);
//			else if(bv_review.isShown()) 
//				frameActiveBtnOnClick(framebtn_Active_comment, ActiveList.CATALOG_COMMENT, Constant.LISTVIEW_ACTION_CHANGE_CATALOG);
//			else if(bv_message.isShown())
//				frameActiveBtnOnClick(framebtn_Active_message, 0, Constant.LISTVIEW_ACTION_CHANGE_CATALOG);
		}
    }
    /**
     * 初始化快捷栏
     */
    private void initQuickActionGrid() {
        mGrid = new QuickActionGrid(this);
        mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_login, R.string.main_menu_login));
        mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_myinfo, R.string.main_menu_myinfo));
        mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_software, R.string.main_menu_setting));
        mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_search, R.string.main_menu_upgrade));
        mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_setting, R.string.main_menu_about));
        mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_exit, R.string.main_menu_exit));
        
        mGrid.setOnQuickActionClickListener(mActionListener);
    }
    /**
     * 快捷栏item点击事件
     */
    private OnQuickActionClickListener mActionListener = new OnQuickActionClickListener() {
        public void onQuickActionClicked(QuickActionWidget widget, int position) {
//    		switch (position) {
//    		case QUICKACTION_LOGIN_OR_LOGOUT://用户登录-注销
//    			Constant.loginOrLogout(Main.this);
//    			break;
//    		case QUICKACTION_USERINFO://我的资料
//    			Constant.showUserInfo(Main.this);
//    			break;
//    		case QUICKACTION_SOFTWARE://开源软件
//    			Constant.showSoftware(Main.this);
//    			break;
//    		case QUICKACTION_SEARCH://搜索
//    			Constant.showSearch(Main.this);
//    			break;
//    		case QUICKACTION_SETTING://设置
//    			Constant.showSetting(Main.this);
//    			break;
//    		case QUICKACTION_EXIT://退出
//    			Constant.Exit(Main.this);
//    			break;
//    		}
        }
    };
    /*
     * 初始化热门转发数据
     */
    private void initRepasteListView(){
    	repasteListViewAdapter = new RepasteListViewAdapter(MainActivity.this,repastes);
    	lvRepaste_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvRepaste_foot_more = (TextView) lvRepaste_footer.findViewById(R.id.listview_foot_more);
    	lvRepaste_foot_progress = (ProgressBar)lvRepaste_footer.findViewById(R.id.listview_foot_progress);
    	repasteListView = (PullToRefreshListView) findViewById(R.id.frame_listview_news);
    	repasteListView.addFooterView(lvRepaste_footer);
    	repasteListView.setAdapter(repasteListViewAdapter);
    	repasteListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this,RepasteDetailActivity.class);
				intent.putExtra("repaste", repastes.get(position-1));
				startActivity(intent);
			}
		});
    	repasteListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				repasteListView.onScrollStateChanged(view, scrollState);
				if(repastes.isEmpty()){
					return;
				}
				boolean isEnd = false;
				try {
					if(view.getPositionForView(lvRepaste_footer) == view.getLastVisiblePosition()){
						isEnd = true;
					}
				} catch (Exception e) {
					isEnd = false;
				}
				if(isEnd){
					lvRepaste_foot_more.setText(R.string.load_ing);
					lvRepaste_foot_progress.setVisibility(View.VISIBLE);
					int pageIndex = StringUtils.convertToInt(repastes.get(repastes.size()-1).getPaging().getNext());
					if(pageIndex!=-1){
						loadLvRepasteData(curHomeCatalog, pageIndex, lvRepasteHandler, Constant.LISTVIEW_ACTION_SCROLL);
					}
				}
			}
		
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				repasteListView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
    	repasteListView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				loadLvRepasteData(curHomeCatalog, 0, lvRepasteHandler, Constant.LISTVIEW_ACTION_REFRESH);
			}
		});
    }
	/**
	 * 初始化圈子列表
	 */
	private void initFriendRepasteListView() {
		// TODO Auto-generated method stub
//		View view = getLayoutInflater().inflate(R.layout.group_name, null);
//		groupListView = (ListView) view.findViewById(R.id.group_name_listView);
//		GroupAdapter groupAdapter = new GroupAdapter(groupIds, MainActivity.this);
//		groupListView.setAdapter(groupAdapter);
//		groupListView.setOnItemClickListener(null);
		friendRepasteListViewAdapter = new RepasteListViewAdapter( MainActivity.this,friendRepastes);
		lvFriend_repaste_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvFriend_repaste_foot_more = (TextView) lvFriend_repaste_footer.findViewById(R.id.listview_foot_more);
    	lvFriend_repaste_foot_progress = (ProgressBar)lvFriend_repaste_footer.findViewById(R.id.listview_foot_progress);
    	friendRepasteListView = (PullToRefreshListView) findViewById(R.id.frame_listview_blog);
    	friendRepasteListView.addFooterView(lvFriend_repaste_footer);
    	friendRepasteListView.setAdapter(friendRepasteListViewAdapter);
    	friendRepasteListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				
			}
		});
    	friendRepasteListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				friendRepasteListView.onScrollStateChanged(view, scrollState);
				if(friendRepastes.isEmpty()){
					return;
				}
				boolean isEnd = false;
				try {
					if(view.getPositionForView(lvFriend_repaste_footer) == view.getLastVisiblePosition()){
						isEnd = true;
					}
				} catch (Exception e) {
					isEnd = false;
				}
				if(isEnd){
					lvFriend_repaste_foot_more.setText(R.string.load_ing);
					lvFriend_repaste_foot_progress.setVisibility(View.VISIBLE);
					int pageIndex = StringUtils.convertToInt(friendRepastes.get(friendRepastes.size()-1).getPaging().getNext());
					if(pageIndex!=-1){
						loadLvFriendRepasteData(curHomeCatalog, pageIndex, lvFriendRepasteHandler, Constant.LISTVIEW_ACTION_SCROLL);
					}
				}
			}
		
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				friendRepasteListView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
    	friendRepasteListView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				loadLvRepasteData(curHomeCatalog, 0, lvFriendRepasteHandler, Constant.LISTVIEW_ACTION_REFRESH);
			}
		});
	}
	/**
	 * 初始化投票列表
	 */
	private void initFriendRecordListView() {
		// TODO Auto-generated method stub
		friendRecordAdapter = new FriendRecordAdapter( MainActivity.this,friendRecords);
		lvFriend_record_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvFriend_record_foot_more = (TextView) lvFriend_record_footer.findViewById(R.id.listview_foot_more);
    	lvFriend_record_foot_progress = (ProgressBar)lvFriend_record_footer.findViewById(R.id.listview_foot_progress);
    	friendRecordListView = (PullToRefreshListView) findViewById(R.id.frame_listview_recommend);
    	friendRecordListView.addFooterView(lvFriend_record_footer);
    	friendRecordListView.setAdapter(friendRecordAdapter);
    	friendRecordListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				
			}
		});
    	friendRecordListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				friendRecordListView.onScrollStateChanged(view, scrollState);
				if(friendRecords.isEmpty()){
					return;
				}
				boolean isEnd = false;
				try {
					if(view.getPositionForView(lvFriend_record_footer) == view.getLastVisiblePosition()){
						isEnd = true;
					}
				} catch (Exception e) {
					isEnd = false;
				}
				if(isEnd){
					lvFriend_record_foot_more.setText(R.string.load_ing);
					lvFriend_record_foot_progress.setVisibility(View.VISIBLE);
					int pageIndex = StringUtils.convertToInt(friendRecords.get(friendRecords.size()-1).getPaging().getNext());
					if(pageIndex!=-1){
						loadLvFriendRecordData(curHomeCatalog, pageIndex, lvFriendRecordHandler, Constant.LISTVIEW_ACTION_SCROLL);
					}
				}
			}
		
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				friendRecordListView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
    	friendRecordListView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				loadLvRepasteData(curHomeCatalog, 0, lvFriendRecordHandler, Constant.LISTVIEW_ACTION_REFRESH);
			}
		});
	}
    
//    class NewTask extends LoadingDialog<String, List<Repaste>>{
//
//		public NewTask(Activity activity, int loadingMsg, int failMsg) {
//			super(activity, loadingMsg, failMsg);
//		}
//
//		@Override
//		public List<Repaste> doInBackground(String... params) {
//			// TODO Auto-generated method stub
//			Bundle bundle  = null;
//			if(!StringUtils.isEmpty(params)){
//				bundle = new Bundle();
//				bundle.putString("start", params[0]);
//			}
//			String json = AppHelper.getFriendActive(MainActivity.instance.kaixin, MainActivity.this, Repaste.PATH_STRING, bundle, "GET");
//			if(StringUtils.isEmpty(json)){
//				return null;
//			}
//			List<Repaste> lists = new RepasteParse().parseData(json);
//			return lists;
//		}
//
//		@Override
//		public void doStuffWithResult(List<Repaste> lists) {
//			// TODO Auto-generated method stub
//			if(StringUtils.isEmpty(lists)){
//				MessageBoxUtils.showMessage(MainActivity.this, R.string.parse_data_fail);
//				return;
//			}
//				repastes = lists;
//			repasteListViewAdapter.setLists(lists);
//		}
//    	
//    }
	class UserTask extends AsyncTask<Void, Void, User>{

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected User doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String json = AppHelper.getFriendActive(kaixin, MainActivity.this, User.PATH_STRING, User.getBundle(), "GET");
			return new UserParse().parseData(json).get(0);
		}

		@Override
		protected void onPostExecute(User result) {
			// TODO Auto-generated method stub
			MainApplication.user = result;
			usernameTextView.setText(result.getName());
			super.onPostExecute(result);
		}
		
	}
	class CircleTask extends AsyncTask<Void, Void, List<Group>>{

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected List<Group> doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String json = AppHelper.getCircleIds(MainActivity.instance.kaixin, MainActivity.this, "/rgroup/groups.json");
			return new GroupParse().parseData(json);
		}
		/* 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(List<Group> result) {
			// TODO Auto-generated method stub
			groupIds = result;
			super.onPostExecute(result);
		}
	}
}